package com.ruoyi.pingjiao.controller;

import com.alibaba.fastjson.JSON;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiV2UserGetuserinfoRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiV2UserGetuserinfoResponse;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.pingjiao.domain.Student;
import com.ruoyi.pingjiao.domain.Teacher;
import com.ruoyi.pingjiao.service.IStudentService;
import com.ruoyi.pingjiao.service.ITeacherService;
import com.ruoyi.system.service.ISysUserService;
import com.taobao.api.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 钉钉企业内部微应用DEMO, 实现了身份验证（免登）功能
 * 陈建彪 在这个上面做修改
 */
@RestController
@CrossOrigin("*") // NOTE：此处仅为本地调试使用，为避免安全风险，生产环境请勿设置CORS为 '*'
public class AuthController2 {
    private static final Logger log = LoggerFactory.getLogger(AuthController2.class);


    @Autowired
    ISysUserService sysUserService;
    @Autowired
    SysLoginService sysLoginService;
    @Autowired
    SysPermissionService permissionService;
    @Autowired
    TokenService tokenService;
    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private IStudentService studentService;

    @Value("${dingding.teacher.app_key}")
    private String appKeyForTeacher;
    @Value("${dingding.student.app_key}")
    private String appKeyForStudent;
    @Value("${dingding.teacher.app_secret}")
    private String appSecretForTeacher;
    @Value("${dingding.student.app_secret}")
    private String appSecretForStudent;



    /**
     * 教师从钉钉端登录，获取当前登录用户的userId并与本系统中的user表进行比较。
     * @author hpf
     * @param authCode 免登临时authCode
     * @return 当前用户
     */
    @GetMapping("/ddLogin1")
    public AjaxResult ddLogin(@RequestParam String authCode) {
        String ddUserIdOfStudent ="0";
        String ddUserIdOfTeacher ="0";
        String ddUserId ="0";
        // 获取钉钉userId
        ddUserIdOfStudent = getDDUserId(authCode,appKeyForStudent,appSecretForStudent);
        if(ddUserIdOfStudent==null){
            ddUserIdOfTeacher = getDDUserId(authCode,appKeyForTeacher,appSecretForTeacher);
            if(ddUserIdOfTeacher==null){
                return   AjaxResult.error("获取钉钉信息失败");
            }else{
                ddUserId=ddUserIdOfTeacher;
            }
        }else{
            ddUserId=ddUserIdOfStudent;
        }
            //判断user表中是否包含钉钉userId
            SysUser user = sysUserService.selectUserByDDuserId(ddUserId);
            if (StringUtils.isNull(user)) {
                return AjaxResult.error(201, "登录用户不存在.");
            } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
                return AjaxResult.error(202, "对不起，您的账号已被删除");
            } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                return AjaxResult.error(203, "对不起，您的账号已停用");
            }
            LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
            AjaxResult ajax = AjaxResult.success();
            ajax.put("msg", "ok");
            ajax.put(Constants.TOKEN, tokenService.createToken(loginUser));
            return ajax;
    }
    /**
     * 学生从钉钉端登录，获取当前登录用户的userId并与本系统中的user表进行比较。
     * @author hpf
     * @param authCode 免登临时authCode
     * @return 当前用户
     */
//    @GetMapping("/ddLogin2")
//    public AjaxResult ddLogin2(@RequestParam String authCode) {
//        // 获取钉钉userId
//        String ddUserId = getDDUserId(authCode,appKeyForStudent,appSecretForStudent);
////        System.out.println(ddUserId);
//        //判断user表中是否包含钉钉userId
//        SysUser user =  sysUserService.selectUserByDDuserId(ddUserId);
//        if (StringUtils.isNull(user))
//        {
////                log.info("登录用户不存在.");
//            return AjaxResult.error(201,"登录用户不存在.");
//        }
//        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
//        {
//            return AjaxResult.error(202,"对不起，您的账号已被删除");
//        }
//        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
//        {
//            return AjaxResult.error(203,"对不起，您的账号已停用");
//        }
//        LoginUser loginUser =  new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
//        AjaxResult ajax = AjaxResult.success();
//        ajax.put("msg","ok");
//        ajax.put(Constants.TOKEN, tokenService.createToken(loginUser));
//        return ajax;
//    }
    /**
     * 钉钉用户首次登录需注册，获取当前登录用户的userId并与本系统中的user表绑定。
     * @author hpf
     * @param authCode 免登临时authCode
     * @return 当前用户
     */
    @GetMapping("/ddRegister2")
    public AjaxResult ddRegister(@RequestParam String roleFlag,@RequestParam String numb,@RequestParam String authCode) {
        Long userId =0L;
        int role =Integer.parseInt(roleFlag);
        // 获取钉钉userId
        String ddUserId ="0";
        if(role==2){
            ddUserId = getDDUserId(authCode,appKeyForStudent,appSecretForStudent);
            Student student =studentService.selectStudentByNo(numb);
            userId=student.getUserId();
            if(student==null) {
                return  AjaxResult.error("查无此人！学号是否正确！");
            }
        }else if(role==1){
            ddUserId = getDDUserId(authCode,appKeyForTeacher,appSecretForTeacher);
            Teacher teacher =teacherService.selectTeacherByNo(numb);
            userId=teacher.getUserId();
            if(teacher==null) {
                return  AjaxResult.error("查无此人！工号是否正确！");
            }
        }
        if(ddUserId.equals('0')){
          return   AjaxResult.error("获取钉钉信息失败");
        }else {
            SysUser user = sysUserService.selectUserById(userId);
            user.setDdUserId(ddUserId);         //绑定ddUserId
            sysUserService.updateUser2(user);
            LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, tokenService.createToken(loginUser));
            return ajax;
        }
    }
    /**
     * 钉钉用户登录，获取当前登录用户的userId
     * @author hpf
     * @param authCode 免登临时authCode
     * @return 当前dd用户userId
     * 测试方法
     */

    private String  getDDUserId(String authCode,String appKey,String appSecret) {
        String ddUserId="";
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setAppkey(appKey);
        request.setAppsecret(appSecret);
        request.setHttpMethod("GET");
        try {
            OapiGettokenResponse response = client.execute(request);//获取accesstoken
            Map maps = (Map)JSON.parse(response.getBody());//转换accesstoken字符串为map对象
            String access_token = maps.get("access_token").toString();
//            下面开始获取userid
            DingTalkClient getUserInfoClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
            OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
            req.setCode(authCode);
            OapiV2UserGetuserinfoResponse rsp = getUserInfoClient.execute(req, access_token);
            Map resultMap = (Map)JSON.parse(rsp.getBody());
            Map userInfo = (Map)JSON.parse(resultMap.get("result").toString());
            ddUserId = userInfo.get("userid").toString();
            return ddUserId;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return ddUserId;
    }


    /**
     * @author hpf
     *  根据学号或工号查询姓名
     */
    @GetMapping("/getName2")
    public  AjaxResult getName(String roleFlag,String numb){
        String name="";
        if(StringUtils.isEmpty(numb)){
            return  AjaxResult.error("学号或工号不能为空");
        }else if(StringUtils.isEmpty(roleFlag)){
            return  AjaxResult.error("请选择身份");
        }else {
            int role =Integer.parseInt(roleFlag);
            if(role==2){
                Student student =studentService.selectStudentByNo(numb);
                if(student==null) {
                    return  AjaxResult.error("查无此人！学号是否输入正确？");
                }
                else{
                    name=student.getRealName();
                }
            }else if(role==1){
                Teacher teacher =teacherService.selectTeacherByNo(numb);
                if(teacher==null) {
                    return  AjaxResult.error("查无此人！工号是否输入正确？");
                }
                else{
                    name=teacher.getRealName();
                }
            }
        }
        name = "*"+name.substring(1);
        return AjaxResult.success(name);
    }

}
